﻿using HuaYun.FTP;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace HuaYun.FTPUpload.Controls
{
    /// <summary>
    /// UCFileItem.xaml 的交互逻辑
    /// </summary>
    public partial class UCFileItem : UserControl
    {
        #region

        /// <summary>
        /// 父控件
        /// </summary>
        private WrapPanel ParentControl = null;

        /// <summary>
        /// 父窗体选择集合
        /// </summary>
        private Dictionary<string, UCFileItem> DicFileItems = null;

        /// <summary>
        /// 本地路径
        /// </summary>
        public string LocalPath { get; set; }

        /// <summary>
        /// FTP用户名
        /// </summary>
        public string FTPUserName { get; set; }

        /// <summary>
        /// FTP密码
        /// </summary>
        public string FTPPassword { get; set; }

        /// <summary>
        /// FTP服务器地址
        /// </summary>
        public string FTPAddress { get; set; }

        /// <summary>
        /// FTP服务器地址
        /// </summary>
        public int FTPPort { get; set; }

        /// <summary>
        /// 上传对象
        /// </summary>
        private int fileType = 2;

        /// <summary>
        /// 是否正在上传
        /// </summary>
        public bool IsUpload = false;

        /// <summary>
        /// 开始上传
        /// </summary>
        private FTPClient ftpClient = null;

        /// <summary>
        /// 是否完成
        /// </summary>
        public bool IsComplete = false;

        /// <summary>
        /// 是否已出错
        /// </summary>
        public bool IsError = false;

        /// <summary>
        /// 上传至服务器路径
        /// </summary>
        public string ServerUploadPath { get; set; }

        /// <summary>
        /// 返回ftp结果
        /// </summary>
        private FTPResult FtpResult { get; set; }

        /// <summary>
        /// 源图片FTP结果
        /// </summary>
        private FTPResult SourceImageResult { get; set; }

        /// <summary>
        /// 上传百分比
        /// </summary>
        public string Precent = "0%";

        /// <summary>
        /// 新源视频
        /// </summary>
        private string newSourcePath = "";

        #endregion

        public UCFileItem(WrapPanel stackPanel, Dictionary<string, UCFileItem> dicFileItems)
        {
            InitializeComponent();

            ParentControl = stackPanel;
            DicFileItems = dicFileItems;
        }

        private void Grid_MouseEnter(object sender, MouseEventArgs e)
        {
            GridOperation.Visibility = Visibility.Visible;
        }

        private void Grid_MouseLeave(object sender, MouseEventArgs e)
        {
            GridOperation.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// 删除事件 移除控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (ParentControl.Children.Contains(this))
                ParentControl.Children.Remove(this);
            if (DicFileItems.ContainsKey(LocalPath))
                DicFileItems.Remove(LocalPath);
        }

        /// <summary>
        /// 初始化图片视图 FileType 2-图片 1-视频
        /// </summary>
        public void InitImageView(int FileType = 2)
        {
            if (!string.IsNullOrEmpty(LocalPath))
            {
                try
                {
                    fileType = FileType;
                    newSourcePath = LocalPath;
                    if (fileType == 2) // 图片
                    {
                        BitmapImage bi = new BitmapImage(new Uri(LocalPath, UriKind.Absolute));
                        ShowImage.Source = bi;
                    }
                    else // 其他类型
                    {
                        string imageFileName = LocalPath.Substring(LocalPath.LastIndexOf("\\") + 1);
                        imageFileName = imageFileName.Substring(0, imageFileName.LastIndexOf('.'));
                        imageFileName += ".jpg";
                        string saveFilePath = LocalPath.Substring(0, LocalPath.LastIndexOf("\\"));
                        // Todo
                    }
                }
                catch (Exception ex)
                {
                    //Log.Error(ex);
                }
            }
        }

        /// <summary>
        /// 开始上传
        /// </summary>
        public void StartUpload()
        {
            IsUpload = true;
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                lblPrecent.Foreground = new SolidColorBrush(Colors.LightGreen);
                lblPrecent.Content = "正在上传...";
                lblPrecent.Visibility = Visibility.Visible;
            }));
            Thread uploadThread = new Thread(Upload);
            uploadThread.IsBackground = true;
            uploadThread.Start();
            //new Thread(Upload).Start();
        }

        /// <summary>
        /// 上传
        /// </summary>
        private void Upload()
        {
            ftpClient = new FTPClient(FTPAddress, FTPPort, FTPUserName, FTPPassword, FTPModel.Binary, Encoding.Default);

            int result = ftpClient.Connect();
            if (result == 0)
            {
                ftpClient.OnProgressChanged += ftpClient_OnProgressChanged;
                ftpClient.OnCompleted += ftpClient_OnCompleted;
                ftpClient.OnFailed += ftpClient_OnFailed;
                FtpResult = ftpClient.Upload(LocalPath); // 开始上传
            }
            else
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    lblPrecent.Content = "连接服务器失败.";
                }));
        }

        /// <summary>
        /// 进度显示事件
        /// </summary>
        /// <param name="sessionID"></param>
        /// <param name="progress"></param>
        private void ftpClient_OnProgressChanged(string sessionID, string progress)
        {
            try
            {
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    lblPrecent.Content = progress;
                    Precent = progress;
                }));
            }
            catch (Exception ex)
            {
                //Log.Error(ex);
            }
        }

        /// <summary>
        /// 上传完成事件
        /// </summary>
        /// <param name="sessionID"></param>
        private void ftpClient_OnCompleted(string sessionID)
        {
            
        }

        /// <summary>
        /// 上传失败事件
        /// </summary>
        /// <param name="sessionID"></param>
        /// <param name="errorID"></param>
        private void ftpClient_OnFailed(string sessionId, int errorId)
        {
            try
            {
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    lblPrecent.Content = "上传失败:" + errorId;
                    lblPrecent.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red);
                    IsError = true;
                }));
            }
            catch (Exception ex)
            {
                //Log.Error(ex);
            }
        }
    }
}
